<?php

/**
 * Created by wangli.
 * Date: 2018/6/21
 * Time: 17:49
 */
class WeixinWithdraw
{
//    const WECHAT_APPID = 'wx62c4022cf1225d34';                  # 开发者ID(AppID)
//    const WECHAT_MERCHANTID = '1508075331';                # 微信支付商户号
//    const TRANS_APPKEY = 'ffe5be61637e77d5e85c88d40e4b268c';    # 商户平台中设置的交易密钥

    #头号试玩小助手账号
    const WECHAT_APPID = 'wx62c4022cf1225d34';                  # 开发者ID(AppID)
    const WECHAT_MERCHANTID = '1518858531';                     # 微信支付商户号
    const TRANS_APPKEY = 'f1e5be61637e77d5e25c8vd40e4b268c';    # 商户平台中设置的交易密钥
    const WECHAT_APIURL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';


    #构造请求参数
    # amount 单位 元
    public static function genReqParams($user)
    {
        $curtime = time();
        $nonce_str = strtoupper( md5($curtime . mt_rand(0,1000)) );
        $req_param = array(
            'mch_appid' => self::WECHAT_APPID,
            'mchid' => self::WECHAT_MERCHANTID,
            'nonce_str' => $nonce_str,
            'partner_trade_no' => sprintf('%010d', $user['wx_draw_history_id']) . $user['uid'],
            'openid' => $user['weixin'],
            'check_name' => 'FORCE_CHECK',
            're_user_name' => $user['realname'],
            'amount' => $user['credits'],
            'desc' => '头号试玩平台结算',
            'spbill_create_ip' => $user['remote_ip'],
        );
        ksort($req_param);

        $sign_str = '';
        foreach ($req_param as $key => $value){
            $sign_str .= $key . '=' . $value . '&';
        }
        $sign_str .= 'key=' . self::TRANS_APPKEY;
        $req_param['sign'] = strtoupper(md5($sign_str));
        return $req_param;
    }

    #处理请求并响应
    public static function responseMsg($req_param) {
        $req_xml = self::array2Xml($req_param);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, 18);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, self::WECHAT_APIURL);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT, dirname(__FILE__) . '/WeixinWithdraw/apiclient_cert.pem');
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, dirname(__FILE__) . '/WeixinWithdraw/apiclient_key.pem');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $req_xml);
        $resp_xml = curl_exec($ch);
        curl_close($ch);
        $ret = array(
            'errcode' => 1,
            'errmsg' => '',
            'descript' => '',
            'succdata' => array()
        );
        if(empty($resp_xml)) {
            $ret['errcode'] = 1;
            $ret['errmsg'] = '微信响应超时';
            return $ret;
        }
        // 解析xml
        $resp_ary = self::xml2Array($resp_xml);
        if(isset($resp_ary['return_code']) && isset($resp_ary['result_code'])) {
            if($resp_ary['return_code'] == 'SUCCESS' && $resp_ary['result_code'] == 'SUCCESS'){
                $ret['errcode'] = 2;
                $ret['errmsg'] = '微信成功支付';
                $ret['succdata'] = array(
                    'payment_no' => $resp_ary['payment_no'],
                    'partner_trade_no' => $resp_ary['partner_trade_no'],
                );
                return $ret;
            } elseif($resp_ary['result_code'] != 'SUCCESS'){
                $ret['errcode'] = 1;
                $ret['errmsg'] = '微信未返回err_code错误信息';
                $err_code = isset($resp_ary['err_code']) ? $resp_ary['err_code'] : '';
                switch ($err_code){
                    case 'OPENID_ERROR':
                        $ret['errmsg'] = '微信提现需要重新绑定微信服务号才可提现！';
                        $retCode = -2;
                        break;
                    case 'NOTENOUGH':
                        $ret['errmsg'] = '请联系客服人员,企业账户余额不足!';
                        break;
                    case 'NAME_MISMATCH':
                        $ret['errmsg'] = '请确认提款姓名和微信绑定的银行卡姓名一致!';
                        break;
                    case 'SYSTEMERROR':
                        self::responseMsg($req_param);   //不能直接去再次请求，而要查询上次的订单号状态
                        $ret['errmsg'] = '微信服务器繁忙,请稍后再试!';
                        break;
                    case 'FREQ_LIMIT':
                        $ret['errmsg'] = '您操作过于频繁，请稍后再试!';
                        break;
                    case 'SENDNUM_LIMIT':
                        $ret['errmsg'] = '今日领取红包个数超过限制!';
                        break;
                    default :
                        $ret['errmsg'] = '提现异常,请联系客服人员.错误码：' . $err_code;
                        break;
                }
                return $ret;
            } elseif($resp_ary['return_code'] != 'SUCCESS') {
                $ret['errcode'] = 1;
                $ret['errmsg'] = isset($resp_ary['return_msg']) ? $resp_ary['return_msg'] : '微信未返回return_code错误信息';
                return $ret;
            }
        }
        $ret['errcode'] = 1;
        $ret['errmsg'] = '微信返回非协议格式数据';
        return $ret;

    }

    /**
     * 微信转账数组转化为xml格式
     */
    static function array2Xml($aryParam){
        $xml = "<xml>";
        foreach ($aryParam as $key => $val){
            //if (is_numeric($val)){
            $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            //}else{
            //	$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            //}
        }
        $xml .= "</xml>";
        return $xml;
    }

    /**
     * 微信转账xml转化为数组
     */
    static function xml2Array($xml){
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }


}